package red.internal.core.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import red.internal.core.message.Message;

/**
 * @author Jin Zheng
 * @since 2020-05-16
 */
public class SenderListener implements ChannelFutureListener
{
	private static Logger logger = LoggerFactory.getLogger(SenderListener.class);

	private final Message message;

	public SenderListener(Message message)
	{
		this.message = message;
	}

	@Override
	public void operationComplete(ChannelFuture future) throws Exception
	{
		Channel ch = future.channel();
		if (future.isSuccess())
		{
			if (logger.isDebugEnabled())
			{
				logger.debug("Send successful to {}: {} 0x{}, channelId: {}", ch.remoteAddress(),
						message.getProtocol(), Long.toHexString(message.getMessageId()), ch.id());
			}
		}
		else
		{
			if (logger.isDebugEnabled())
			{
				logger.warn("Send failure to {}: {} 0x{}, channelId: {}", ch.remoteAddress(),
						message.getProtocol(), Long.toHexString(message.getMessageId()), ch.id());
			}
		}
		Throwable throwable = future.cause();
		if (throwable != null)
		{
			logger.error("Occur exception: ", throwable);
		}
	}
}
